<template>
  <div class="mpb-wrapper">
    <div class="mpb-time-select">
      <div :class="{'current': dateType === 2}" @click="changeTimeType(2)">周报</div>
      <div :class="{'current': dateType === 3}" @click="changeTimeType(3)">月报</div>
      <div :class="{'current': dateType === 4}" @click="changeTimeType(4)">季报</div>
    </div>
    <div class="block" style="width: 600px; margin: 0 auto;">
      <el-slider
        v-model="value"
        show-stops
        :format-tooltip="formatTooltip"
        :min="1"
        @change="changeTime"
        :max="maxLength">
      </el-slider>
    </div>
    <div class="chart-wrapper">
      <div class="chart-item">
        <div ref="echart1" class="echart-class"></div>
        <p class="total">{{totalTimeRange}} 整体{{totalName0}}(美元)：{{total.total0}}</p>
        <div ref="echart2" class="echart-class"></div>
      </div>
      <div class="chart-item">
        <div ref="echart3" class="echart-class"></div>
        <p class="total">{{totalTimeRange}} 整体{{totalName2}}：{{total.total2}}</p>
        <div ref="echart4" class="echart-class"></div>
      </div>
    </div>
  </div>
</template>

<script>
  import {dateUtil} from '@/utils/dateUtil'
  import dingMixin from  '@/mixins/ding'

  export default {
    data () {
      return {
        value: 6,
        chart1: null,
        chart2: null,
        chart3: null,
        chart4: null,
        totalName0: '',
        totalName2: '',
        total: {
          total0: 0,
          total2: 0
        },
        totalTimeRange: '',
        dateType: 2,
        monthSelect: [],
        maxLength: 12,
        quarterSelect: [],
        requestUrl: [{
          url:'crm/report/categorySaleReport',
          title: '种类销售额'
        },{
          url:'crm/report/categoryCountReport',
          title: '种类销量'
        }],
        requestUrl2: [{
          url:'crm/report/productSaleReport',
          title: '产品销售额'
        },{
          url:'crm/report/productCountReport',
          title: '产品销量'
        }],
        resuleData: {},
        resultData2: {},
        level: 1,
        childId: ''
      }
    },
    components: {
    },
    beforeDestroy() {
      this.$parent.cpglMenus = [];
    },
    mixins: [dateUtil, dingMixin],
    async mounted(){
      this.getData(this.value)
      this.initMonthSelect()
      this.initQuarterSelect()
    },
    methods: {
      initMonthSelect() {
        let date = dateUtil.thisMonth().split('-');
        for(let i = 0; i< 12; i++ ){
          if((parseInt(date[1]) - i) >=1){
            this.monthSelect.push(`${date[0]}-${('0' + (date[1] - i)).substr(-2)}`)
          }else{
            this.monthSelect.push(`${parseInt(date[0]) - 1}-${('0' + (date[1] - i + 12)).substr(-2)}`)
          }
        }
      },
      changeTab(tab) {
        this.$router.push({ name: 'mmpb-' + tab})
      },
      initQuarterSelect() {
        let date = dateUtil.thisMonth().split('-');
        if(parseInt(date[1]) <=3 ) {
          this.quarterSelect.push(`${parseInt(date[0])}.01-${parseInt(date[0])}.03`
          , `${parseInt(date[0]) - 1}.10-${date[0] - 1}.12`
          , `${parseInt(date[0]) -1}.07-${parseInt(date[0]) -1}.09`
          , `${parseInt(date[0])-1}.04-${parseInt(date[0])-1}.06`
          , `${parseInt(date[0]) -1}.01-${parseInt(date[0])}.03`
          , `${parseInt(date[0]) - 2}.10-${date[0] - 2}.12`
          , `${parseInt(date[0]) -2}.07-${parseInt(date[0]) -2}.09`
          , `${parseInt(date[0])-2}.04-${parseInt(date[0]) -2}.06`)
        }else if(parseInt(date[1]) >3 && parseInt(date[1]) <=6) {
          this.quarterSelect.push(`${parseInt(date[0])}.04-${parseInt(date[0])}.06`
          ,`${parseInt(date[0])}.01-${parseInt(date[0])}.03`
          , `${parseInt(date[0]) - 1}.10-${date[0] - 1}.12`
          , `${parseInt(date[0]) -1}.07-${parseInt(date[0]) -1}.09`
          , `${parseInt(date[0])-1}.04-${parseInt(date[0])-1}.06`
          , `${parseInt(date[0]) -1}.01-${parseInt(date[0])}.03`
          , `${parseInt(date[0]) - 2}.10-${date[0] - 2}.12`
          , `${parseInt(date[0]) -2}.07-${parseInt(date[0]) -2}.09`)
        }else if(parseInt(date[1]) >6 && parseInt(date[1]) <= 9) {
          this.quarterSelect.push(`${parseInt(date[0])}.06-${parseInt(date[0])}.09`
          , `${parseInt(date[0])}.04-${parseInt(date[0])}.06`
          , `${parseInt(date[0])}.01-${parseInt(date[0])}.03`
          , `${parseInt(date[0]) - 1}.10-${date[0] - 1}.12`
          , `${parseInt(date[0]) -1}.07-${parseInt(date[0]) -1}.09`
          , `${parseInt(date[0])-1}.04-${parseInt(date[0])-1}.06`
          , `${parseInt(date[0]) -1}.01-${parseInt(date[0])}.03`
          , `${parseInt(date[0]) - 2}.10-${date[0] - 2}.12`)
        }else if(parseInt(date[1]) >9) {
          this.quarterSelect.push(`${parseInt(date[0])}.10-${parseInt(date[0])}.12`
          , `${parseInt(date[0])}.06-${parseInt(date[0])}.09`
          , `${parseInt(date[0])}.04-${parseInt(date[0])}.06`
          , `${parseInt(date[0])}.01-${parseInt(date[0])}.03`
          , `${parseInt(date[0]) - 1}.10-${date[0] - 1}.12`
          , `${parseInt(date[0]) -1}.07-${parseInt(date[0]) -1}.09`
          , `${parseInt(date[0])-1}.04-${parseInt(date[0])-1}.06`
          , `${parseInt(date[0]) -1}.01-${parseInt(date[0])}.03`)
        }
      },
      changeTimeType(type) {
        this.dateType = type;
        if(type === 4) {
          this.maxLength = 8;
          this.value = 4;
        }else {
          this.maxLength = 12;
          this.value = 6;
        }
        if(this.level === 1) {
          this.getData(this.value)
        }else {
          this.getChildData();
        }
      },
      changeTime() {
        if(this.level === 1) {
          this.getData(this.value)
        }else {
          this.getChildData();
        }
      },
      formatTooltip(val) {
        return `最近${val}${this.dateType === 2 ? '周': this.dateType === 4 ? '季度':'月'}`;
      },
      async getData(val) {
        let to;
        let from
        if(this.dateType === 2) {
          from = dateUtil.nDaysBefore(7*(val - 1));
          to = dateUtil.thisDay();
        }else if(this.dateType === 3) {
          from = this.monthSelect[val-1];
          to = this.monthSelect[0]
        }else if(this.dateType === 4) {
          from = this.quarterSelect[val-1];
          to = this.quarterSelect[0]
        }

        let postParam = {
          from,
          to,
          dateType: this.dateType
        }

        this.requestUrl.forEach(async (item, idx) => {
          let data = await this.$httpN.postB(item.url, postParam);
          this.setPieData(data, idx*2, item.title)
          this.setLineData(data, idx*2)
          if(this.dateType === 2) {
            if(this.value > 1) {
              this.totalTimeRange = `${data.dates[0].split('到')[0]} 到 ${data.dates[data.dates.length - 1].split('到')[1]}`
            }else{
              this.totalTimeRange = `${data.dates[0]}`
            }
          }else{
            if(this.value > 1) {
              this.totalTimeRange = `${data.dates[0]} 到 ${data.dates[data.dates.length - 1]}`
            }else{
              this.totalTimeRange = `${data.dates[0]}`
            }
          }
          this['resuleData' + idx*2] = data;
        })
      },
      getChildData() {
        let val = this.value;
        let to;
        let from;
        if(this.dateType === 2) {
          from = dateUtil.nDaysBefore(7*(val - 1));
          to = dateUtil.thisDay();
        }else if(this.dateType === 3) {
          from = this.monthSelect[val-1];
          to = this.monthSelect[0]
        }else if(this.dateType === 4) {
          from = this.quarterSelect[val-1];
          to = this.quarterSelect[0]
        }

        let postParam = {
          from,
          to,
          dateType: this.dateType,
          dataId: this.childId
        }

        this.requestUrl2.forEach(async (item, idx) => {
          let data = await this.$httpN.postB(item.url, postParam);
          this.setPieData(data, idx*2, item.title)
          this.setLineData(data, idx*2)
          if(this.dateType === 2) {
            if(this.value > 1) {
              this.totalTimeRange = `${data.dates[0].split('到')[0]} 到 ${data.dates[data.dates.length - 1].split('到')[1]}`
            }else{
              this.totalTimeRange = `${data.dates[0]}`
            }
          }else{
            if(this.value > 1) {
              this.totalTimeRange = `${data.dates[0]} 到 ${data.dates[data.dates.length - 1]}`
            }else{
              this.totalTimeRange = `${data.dates[0]}`
            }
          }
          this['resuleData' + idx*2] = data;
        })
      },
      setPieData(data, num, title) {
        let that = this;
        if(!this['chart' + (num + 1)]) {
          this['chart' + (num + 1)] = echarts.init(this.$refs['echart' + (num + 1)]);
          this['chart' + (num + 1)].on('click', 'series.pie', function (params) {
            if(that.level === 2) return;
            that.childId = that['resuleData' + num].ids[params.name];
            that.$parent.cpglMenus = [{id: that['resuleData' + num].ids[params.name], name: params.name}];
            that.level = 2;
            that.getChildData()
          });
        };
        let pieData = [];
        let traverseObj = data.ids === ''? data.values: data.ids
        for(let key in traverseObj) {
          if(data.values[key]) {
            let sum = data.values[key].reduce((prev, curr) => prev + curr);
            if(sum > 0 && key !== '整体业绩') {
              pieData.push({name: key, value: sum})
            }
          }
        }
        this.total['total' + num] = data.total;
        this['totalName' + num] = title;
        this['chart' + (num + 1)].setOption({
          title: {
            text: title,
            left: 'center',
            textStyle: {
              fontWeight: 'normal',
              fontSize: 14
            }
          },
          tooltip: {
            trigger: 'item',
            confine: true,
            enterable: true,
            formatter: (params) => {
              if(this.level === 1) {
                return `<span>${params.name}:${params.value}(${params.percent}%)</span><br><span>查看详情</span>`
              }else {
                return `<span>${params.name}:${params.value}(${params.percent}%)</span>`
              }
            },
          },
          series: [{
            type: 'pie',
            radius: '65%',
            center: ['50%', '60%'],
            data: pieData,
            emphasis: {
              itemStyle: {
                shadowBlur: 10,
                shadowOffsetX: 0,
                shadowColor: 'rgba(0, 0, 0, 0.5)'
              }
            },
            label: {
            }
          }]
        })
      },
      setLineData(data, num) {
        let that = this;
        if(!this['chart' + (num + 2)]) this['chart' + (num + 2)] = echarts.init(this.$refs['echart' + (num + 2)]);
        let lineData = [];
        let legendData = [];
        let xAxisData = []
        let traverseObj = data.ids === ''? data.values: data.ids
        for(let key in traverseObj) {
          if(data.values[key]) {
            let sum = data.values[key].reduce((prev, curr) => prev + curr);
            if(sum >0) {
              lineData.push({name: key, type: 'line', data: data.values[key]})
              legendData.push(key)
            }
          }
        }
        xAxisData.push(...data.dates)
      
        let interval = 0;
        if(this.dateType === 2 && this.value > 8) interval = 1; 
        if(this.dateType === 3 && this.value > 6) interval = 1; 

        let option2 = {
          tooltip: {
              trigger: 'axis'
          },
          legend: {
            data: legendData,
            type: 'scroll'
          },
          grid: {
              left: '3%',
              right: '4%',
              bottom: '3%',
              containLabel: true
          },
          xAxis: {
              type: 'category',
              boundaryGap: false,
              data: xAxisData,
              axisLabel:{
                align: 'center',
                interval: interval,
                fontSize: 12,
                formatter: function (value, index) {
                  if(that.dateType === 4) {
                    let result = value.replace('-', '');
                    return result.substr(-4);
                  }else if(that.dateType === 3) {
                    let result = value.replace(/月/g, '');
                    result = result.replace(/-/g, '.');
                    return result 
                  }else if(that.dateType === 2) {
                    let result = value.substr(-5);
                    result = result.split('-');
                    return `${parseInt(result[0])}.${parseInt(result[1])}`
                  }
                }
              }
          },
          yAxis: {
            type: 'value',
            axisLabel: {
              formatter: function (value, index) {
                if(value < 1000) {
                  return value
                }else if(value < 1000000 && value > 1000) {
                  return value / 1000 + 'K'
                }else {
                  return value / 1000000 + 'M'
                }
              }
            }
          },
          series: lineData
        };
        this['chart' + (num + 2)].clear();
        this['chart' + (num + 2)].setOption(option2);
      }
    }
  }
</script>

<style lang="scss">
  .mpb-wrapper{
    overflow:hidden;
    width: 100%;
    padding: 12px;
    .mpb-time-select{
      width: 600px;
      margin: 0 auto;
      display: flex;
      >div{
        display: block;
        position: relative;
        -webkit-box-flex: 1;
        -webkit-flex: 1;
        flex: 1;
        width: 100%;
        height: 30px;
        padding: 0;
        font-size: 14px;
        line-height: 28px;
        text-align: center;
        color: #999;
        white-space: nowrap;
        background: #fdfdfd;
        -webkit-tap-highlight-color: rgba(255,0,0,0);
        border: 1px solid #ccc;
      }
      >div:first-child{
        border-top-left-radius: 32px;
        border-bottom-left-radius: 32px;
        border-right-width: 0;
      }
      >div:last-child{
        border-top-right-radius: 32px;
        border-bottom-right-radius: 32px;
        border-left-width: 0;
      }
      div.current{
        color: #000;
        background: #ffe26d;
      }
    }
    .total{
      text-align: center;
      margin: 30px 0;
    }
    .chart-wrapper{
      display: flex;
      .chart-item{
        flex: 1;
      }
    }
  }
  .echart-class{
    width: 100%;
    height: calc((100vh - 220px) / 2);
  }
  .component-tabbar{
    position:fixed;
    bottom:0;
    left: 0;
    width: 100%;
    text-align: center;
    background: #FFF;
    box-shadow: 0 0 10px 0 hsla(0,6%,58%,.6);
    z-index: 99;
    display: flex;
    .tab{
      flex: 1;
      line-height: 46px;
      p{
        margin: 0;
        color: #969696;
        &.active{
          color: #42A5F5;
        }
      }
    }
  }
  .currentPath{
    font-weight: bold;
    margin-bottom: 10px;
  }
</style>